<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * addiadj.php
 * Began: Sun January 5 2003
 * 
 * $Id: addiadj.php 541 2008-05-20 06:56:16Z rspeicher $
 * 
 ******************************/
 
define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

$fv = new Form_Validate;

// Obtain var settings
$adjustment_id = ( !empty($_REQUEST[URI_ADJUSTMENT]) ) ? intval($_REQUEST[URI_ADJUSTMENT]) : '';
$confirm = ( !empty($_POST['confirm']) ) ? true : false;

// Start session management
$user->start();
$user->setup();

// Delete confirmation
// If they didn't confirm, redirect them to the last page they were on
if ( isset($_POST['cancel']) )
{
    if ( $adjustment_id )
    {
        $redirect = 'addiadj.php'.$SID.'&' . URI_ADJUSTMENT . '='.$adjustment_id;
    }
    else
    {
        $redirect = 'addiadj.php'.$SID;
    }

    redirect($redirect);
}

// Figure out what submit button was pressed
$add    = ( isset($_POST['add']) ) ? true : false;
$update = ( isset($_POST['update']) ) ? true : false;
$delete = ( isset($_POST['delete']) ) ? true : false;

// Figure out action based on submit
if ( $add )
{
    $user->check_auth('a_indivadj_add');
    $action = 'add';
}
elseif ( $update )
{
    $user->check_auth('a_indivadj_upd');
    $action = 'update';
}
elseif ( ($delete) || ($confirm) )
{
    $user->check_auth('a_indivadj_del');
    $action = 'delete';
}
else
{
    $user->check_auth('a_indivadj_');
    $action = 'display';
}

//
// Error Checking and variable initialization
//
if ( ($add) || ($update) || ($delete) )
{
    $_POST = htmlspecialchars_array($_POST);
    
    $adjustment_added_by = $user->data['username'];
    $adjustment_updated_by = $user->data['username'];
    
    if ( (!isset($_POST['member_names'])) || (!is_array($_POST['member_names'])) )
    {
        $fv->errors['member_names'] = $user->lang['fv_required_members'];
    }
    
    $fv->is_number('adjustment_value', $user->lang['fv_number_adjustment']);
    $fv->is_filled('adjustment_value', $user->lang['fv_required_adjustment']);
    $fv->is_within_range('mo', 1, 12, $user->lang['fv_range_month']);
    $fv->is_within_range('d', 1, 31, $user->lang['fv_range_day']);
    $fv->is_within_range('y', 1998, 2010, $user->lang['fv_range_year']);
    
    $adjustment_date = mktime(0, 0, 0, $_POST['mo'], $_POST['d'], $_POST['y']);
    
    if ( $fv->is_error() )
    {
        $action = 'display';
    }
}

//
// Get relevant data
//
if ( $adjustment_id )
{
    $sql = 'SELECT adjustment_value, adjustment_date, adjustment_reason, member_name, adjustment_group_key
            FROM ' . ADJUSTMENTS_TABLE . "
            WHERE adjustment_id='".$adjustment_id."'";
    $result = $db->query($sql);
    if ( !$row = $db->fetch_record($result) )
    {
        message_die($user->lang['error_invalid_adjustment_provided']);
    }
    $db->free_result($result);

    // If member name isn't set, it's a group adjustment - put them back on that script
    if ( !isset($row['member_name']) )
    {
        redirect('addadj.php' . $SID . '&' . URI_ADJUSTMENT . '='.$adjustment_id);
    }
    
    $current_date = $row['adjustment_date'];
    $adjustment = array(
        'adjustment_value' => post_or_db('adjustment_value', true, $row),
        'adjustment_reason' => post_or_db('adjustment_reason', true, $row)
    );
    
    $sql = 'SELECT member_name
            FROM ' . ADJUSTMENTS_TABLE . "
            WHERE adjustment_group_key='".$row['adjustment_group_key']."'";
    $result = $db->query($sql);
    while ( $mrow = $db->fetch_record($result) )
    {
        $members[] = $mrow['member_name'];
    }
    $adjustment['member_names'] = ( !empty($_POST['member_names']) ) ? $_POST['member_names'] : $members;
    unset($members);
}
else
{
    $current_date = time();
    $adjustment = array(
        'adjustment_value' => post_or_db('adjustment_value', false),
        'adjustment_reason' => post_or_db('adjustment_reason', false),
        'member_names' => post_or_db('member_names', false)
    );
}

//
// Processing
//
switch ( $action )
{
    //
    // Add
    //
    case 'add':
        $adjustment_group_key = generate_adjustment_group_key($adjustment_date, stripslashes($_POST['adjustment_reason']), $_POST['adjustment_value']);
        
        $member_names = $_POST['member_names'];
        
        foreach ( $member_names as $k => $v )
        {
            // Add the adjustment to the table
            $sql = 'INSERT INTO ' . ADJUSTMENTS_TABLE . "
                    (adjustment_id, adjustment_value, adjustment_date, member_name, adjustment_reason, adjustment_group_key, adjustment_added_by)
                    VALUES ('NULL','".$_POST['adjustment_value']."','".$adjustment_date."','".$v."','".remove_quote_escape($_POST['adjustment_reason'])."',
                        '".$adjustment_group_key."','".$adjustment_added_by."')";
            $db->query($sql);
            
            // Add the adjustment to the member
            $sql = 'UPDATE ' . MEMBERS_TABLE . "
                    SET member_adjustment = member_adjustment+".$_POST['adjustment_value']."
                    WHERE member_name='".$v."'";
            $db->query($sql);
        }
        
        // Logging
        $log_action = array(
            'header' => '{L_ACTION_INDIVADJ_ADDED}',
            '{L_ADJUSTMENT}' => $_POST['adjustment_value'],
            '{L_MEMBERS}' => implode(', ', $member_names),
            '{L_REASON}' => $_POST['adjustment_reason'],
            '{L_ADDED_BY}' => $adjustment_added_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );
        
        $success_message = sprintf($user->lang['admin_add_iadj_success'], $eqdkp->config['dkp_name'], $_POST['adjustment_value'], implode(', ', $member_names));
        
        $link_list = generate_admin_success_links(array(
            $user->lang['list_indivadj'] => 'listadj.php' . $SID . '&amp;' . URI_PAGE . '=individual',
            $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
        );
        
        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
        
        break;
    //
    // Update
    //
    case 'update':
        // Remove the 'old' adjustment from each of the previous members
        $sql = 'SELECT a2.*
                FROM ( ' . ADJUSTMENTS_TABLE . ' a1
                LEFT JOIN ' . ADJUSTMENTS_TABLE . " a2
                ON a1.adjustment_group_key = a2.adjustment_group_key )
                WHERE a1.adjustment_id='".$adjustment_id."'";
        $result = $db->query($sql);
        $old_members = array();
        while ( $row = $db->fetch_record($result) )
        {
            $db->query('DELETE FROM ' . ADJUSTMENTS_TABLE . " WHERE adjustment_id='".$row['adjustment_id']."'");
            $db->query('UPDATE ' . MEMBERS_TABLE . " SET member_adjustment = member_adjustment-".$row['adjustment_value']." WHERE member_name='".$row['member_name']."'");
            
            $old_members[] = addslashes($row['member_name']);
            
            $old_adjustment = array(
                'adjustment_value' => addslashes($row['adjustment_value']),
                'adjustment_date' => addslashes($row['adjustment_date']),
                'member_names' => $old_members,
                'adjustment_reason' => addslashes($row['adjustment_reason']));
        }
        
        // All of the 'old' adjustments with this group key are gone
        // Add the new adjustments with new group keys and (maybe) new members
        $adjustment_group_key = generate_adjustment_group_key($adjustment_date, stripslashes($_POST['adjustment_reason']), $_POST['adjustment_value']);
        
        $member_names = $_POST['member_names'];
        
        foreach ( $member_names as $k => $v )
        {
            // Add the adjustment to the table
            $sql = 'INSERT INTO ' . ADJUSTMENTS_TABLE . "
                    (adjustment_id, adjustment_value, adjustment_date, member_name, adjustment_reason, adjustment_group_key, adjustment_added_by)
                    VALUES ('NULL','".$_POST['adjustment_value']."','".$adjustment_date."','".$v."','".remove_quote_escape($_POST['adjustment_reason'])."',
                        '".$adjustment_group_key."','".$adjustment_added_by."')";
            $db->query($sql);
            
            // Add the adjustment to the member
            $sql = 'UPDATE ' . MEMBERS_TABLE . "
                    SET member_adjustment = member_adjustment+".$_POST['adjustment_value']."
                    WHERE member_name='".$v."'";
            $db->query($sql);
        }
        
        // Logging
        $log_action = array(
            'header' => '{L_ACTION_INDIVADJ_UPDATED}',
            'id' => $adjustment_id,
            '{L_ADJUSTMENT_BEFORE}' => $old_adjustment['adjustment_value'],
            '{L_MEMBERS_BEFORE}' => implode(', ', $old_adjustment['member_names']),
            '{L_REASON_BEFORE}' => $old_adjustment['adjustment_reason'],
            '{L_ADJUSTMENT_AFTER}' => find_difference($old_adjustment['adjustment_value'], $_POST['adjustment_value']),
            '{L_MEMBERS_AFTER}' => implode(', ', find_difference($old_adjustment['member_names'], $member_names)),
            '{L_REASON_AFTER}' => find_difference($old_adjustment['adjustment_reason'], $_POST['adjustment_reason']),
            '{L_UPDATED_BY}' => $adjustment_updated_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );
        
        $success_message = sprintf($user->lang['admin_update_iadj_success'], $eqdkp->config['dkp_name'], $_POST['adjustment_value'], implode(', ', $member_names));
        
        $link_list = generate_admin_success_links(array(
            $user->lang['list_indivadj'] => 'listadj.php' . $SID . '&amp;' . URI_PAGE . '=individual',
            $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
        );
        
        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
        
        break;
    //
    // Delete
    //
    case 'delete':
        if ( !$confirm )
        {
            confirm_delete($user->lang['confirm_delete_iadj'], URI_ADJUSTMENT, $adjustment_id, 'addiadj.php'.$SID);
        }
        else
        {
            // Remove the adjustment from each of the previous members
            $sql = 'SELECT a2.*
                    FROM ( ' . ADJUSTMENTS_TABLE . ' a1
                    LEFT JOIN ' . ADJUSTMENTS_TABLE . " a2
                    ON a1.adjustment_group_key = a2.adjustment_group_key )
                    WHERE a1.adjustment_id='".$adjustment_id."'";
            $result = $db->query($sql);
            $old_members = array();
            while ( $row = $db->fetch_record($result) )
            {
                $db->query('DELETE FROM ' . ADJUSTMENTS_TABLE . " WHERE adjustment_id='".$row['adjustment_id']."'");
                $db->query('UPDATE ' . MEMBERS_TABLE . " SET member_adjustment = member_adjustment-".$row['adjustment_value']." WHERE member_name='".$row['member_name']."'");
                
                $old_members[] = addslashes($row['member_name']);
                
                $old_adjustment = array(
                    'adjustment_value' => addslashes($row['adjustment_value']),
                    'adjustment_date' => addslashes($row['adjustment_date']),
                    'member_names' => $old_members,
                    'adjustment_reason' => addslashes($row['adjustment_reason']));
            }
            
            $log_action = array(
                'header' => '{L_ACTION_INDIVADJ_DELETED}',
                'id' => $adjustment_id,
                '{L_ADJUSTMENT}' => $old_adjustment['adjustment_value'],
                '{L_MEMBERS}' => implode(', ', $old_adjustment['member_names']),
                '{L_REASON}' => $old_adjustment['adjustment_reason']);
            $eqdkp->log_insert(array(
                'log_type' => $log_action['header'],
                'log_action' => $eqdkp->make_log_action($log_action),
                'log_ipaddress' => $user->ip,
                'log_sid' => $user->session_id,
                'log_result' => '{L_SUCCESS}',
                'admin_id' => $user->data['user_id'])
            );
            
            $success_message = sprintf($user->lang['admin_delete_iadj_success'], $eqdkp->config['dkp_name'], $old_adjustment['adjustment_value'], implode(', ', $old_adjustment['member_names']));
            
            $link_list = generate_admin_success_links(array(
                $user->lang['list_indivadj'] => 'listadj.php' . $SID . '&amp;' . URI_PAGE . '=individual',
                $user->lang['list_members'] => $eqdkp_root_path.'listmembers.php'.$SID)
            );
            
            message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
            
        } // confirmed
        break;
    //
    // Display form
    //
    case 'display':
        // Member names drop-down
        $result = $db->query('SELECT member_name FROM ' . MEMBERS_TABLE . ' ORDER BY member_name');
        while ( $row = $db->fetch_record($result) )
        {
            if ( $adjustment_id )
            {
                $selected = ( @in_array($row['member_name'], $adjustment['member_names']) ) ? ' selected="selected"' : '';
            }
            else
            {
                $selected = ( @in_array($row['member_name'], $_POST['member_names']) ) ? ' selected="selected"' : '';
            }
            
            $tpl->assign_block_vars('members_row', array(
                'VALUE' => $row['member_name'],
                'SELECTED' => $selected,
                'OPTION' => $row['member_name'])
            );
        }
        $db->free_result($result);
        
        $tpl->assign_vars(array(
            'F_ADD_ADJUSTMENT' => 'addiadj.php'.$SID,
            'ADJUSTMENT_ID' => $adjustment_id,
            
            'ADJUSTMENT_VALUE' => $adjustment['adjustment_value'],
            'ADJUSTMENT_REASON' => stripslashes($adjustment['adjustment_reason']),
            'MO' => date('m', stripslashes($current_date)),
            'D' => date('d', stripslashes($current_date)),
            'Y' => date('Y', stripslashes($current_date)),
            'H' => date('h', stripslashes($current_date)),
            'MI' => date('i', stripslashes($current_date)),
            'S' => date('s', stripslashes($current_date)),
            
            'L_ADD_IADJ_TITLE' => $user->lang['addiadj_title'],
            'L_MEMBERS' => $user->lang['members'],
            'L_HOLD_CTRL_NOTE' => '(' . $user->lang['hold_ctrl_note'] . ')<br />',
            'L_REASON' => $user->lang['reason'],
            'L_VALUE' => $user->lang['value'],
            'L_ADJUSTMENT_VALUE_NOTE' => strtolower($user->lang['adjustment_value_note']),
            'L_DATE' => $user->lang['date'],
            'L_ADD_ADJUSTMENT' => $user->lang['add_adjustment'],
            'L_RESET' => $user->lang['reset'],
            'L_UPDATE_ADJUSTMENT' => $user->lang['update_adjustment'],
            'L_DELETE_ADJUSTMENT' => $user->lang['delete_adjustment'],
            
            'FV_MEMBERS' => $fv->generate_error('member_names'),
            'FV_ADJUSTMENT' => $fv->generate_error('adjustment_value'),
            'FV_MO' => $fv->generate_error('mo'),
            'FV_D' => $fv->generate_error('d'),
            'FV_Y' => $fv->generate_error('y'),
            
            'MSG_VALUE_EMPTY' => $user->lang['fv_required_adjustment'],
            
            'S_ADD' => ( !$adjustment_id ) ? true : false)
        );
        
        $page_title = sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['addiadj_title'];
        include_once($eqdkp_root_path . 'includes/page_header.php');

        $tpl->set_filenames(array(
            'body' => 'admin/addiadj.html')
        );
        
        include_once($eqdkp_root_path . 'includes/page_tail.php');
        break;
}

/**
* Generate our 32-character group key
* Unique (hopefully) key to group members that received this exact adjustment
* at the same time.
*
* @param $adjustment_date
* @param $adjustment_reason
* @return string Adjustment Group Key
*/
function generate_adjustment_group_key($adjustment_date, $adjustment_reason, $adjustment_value)
{
    $date_part = substr(md5($adjustment_date), 0, 10);
    $reason_part = substr(md5($adjustment_reason), 0, 11);
    $value_part = substr(md5($adjustment_value), 0, 11);
    
    $adjustment_group_key = $date_part . $reason_part . $value_part;
    
    return md5(uniqid($adjustment_group_key));
}
?>